package com.tianqu.tms.www.user.controller;

import java.util.List;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.security.TmsUserProfile;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.entity.User;
import com.tianqu.tms.entity.UserAuth;
import com.tianqu.tms.entity.UserClass;
import com.tianqu.tms.entity.UserRole;
import com.tianqu.tms.www.user.action.UserUpdateResultAction;
import com.tianqu.tms.www.user.viewhelper.UserDetailViewHelper;

/**
 * 修改用户信息结果页面
 * 
 * @author tianshufu
 * 
 */
public class UserUpdateResultController extends TmsController {

	private Logger logger = Logger.getLogger(UserUpdateResultAction.class);

	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#doAction was called.");
		TxController controller = TxController.getTxController();

		// 添加事务提交异常捕获
		try {
			controller.begin();

			TmsUserProfile userprofile = uc.getUserProfile();
			User user = new User();

			UserDetailViewHelper view = (UserDetailViewHelper) uc
					.getAttribute(TmsConstants.VIEWHELP);

			UserClass code = UserClass.getInstance();

			logger.debug("字典表里获取code信息："
					+ code.getUserClassByUserClassName(view.getUserType()));

			// 先把以前的role都给删了，在往里面添加新的role,view.getId()为user表中主键ID
			UserRole role = UserRole.getInstance();
			UserAuth auth = UserAuth.getInstance();

			// 先删除auth表中class下权限
			auth.delUserAuthInfo(Integer.parseInt(view.getId()));

			// 根据userClass查询roleId]
			// 删除之后向AUTH表中重新添加一条权限信息
			List<UserRole> roleList = role.getRoleinfoByUcId(code
					.getUserClassByUserClassName(view.getUserType()),2);

			if (roleList.size() > 0) {
				for (int i = 0; i < roleList.size(); i++) {
					UserRole entity = roleList.get(i);
					auth.insertUserAuthInfo(Integer.parseInt(view.getId()),
							entity.getRole());
				}
			}
			user.updateUserInfoById(view.getId(), code
					.getUserClassByUserClassName(view.getUserType()),
					userprofile.getUniqueId());

			controller.commit();
		} catch (Exception e) {
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				throw e;
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}

		logger.debug(this.getClass().getName() + "#doAction was completed.");
	}

}
